<template>
  <div class="container">
    <!-- 面包屑导航 -->
    <div class="topNav">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ name: 'base' }">仓库系统</el-breadcrumb-item>
        <el-breadcrumb-item>
          <span v-if="props.id">编辑质检单</span>
          <span v-if="!props.id">新增质检单</span>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="together-content">
      <!-- 质检单信息 -->
      <div>
        <el-form :inline="true" label-width="auto" style="width: 100%">
          <!-- 调拨单编码 -->
          <el-form-item label="单据编号" v-if="props.id">
            {{ qualityOrder.code }}
          </el-form-item>

          <!-- 时间范围选择 -->
          <el-form-item label="日期">
            <el-date-picker v-model="datePickerValue" type="date" placeholder="选择日期" size="small" style="width: 150px"
              value-format="YYYY-MM-DD" @change="handleDateChange" />
          </el-form-item>

          <!-- 不需要，关联采购单后有供应商信息  -->
          <!-- <el-form-item label="供应商">
            <el-select style="width: 150px">
              <el-option />
            </el-select>
          </el-form-item> -->

          <!--  -->
          <el-form-item label="关联采购单：">
            <span v-if="qualityOrder.sourceOrderCode"></span>
            <div>
              <el-link type="primary" @click="openCGDialog()" style="margin-right: 20px; cursor: pointer;">
                采购入库源单
              </el-link>
              <el-link type="primary" @click="openSourceOrderDialog(2)" style="cursor: pointer;">
                销售退货源单
              </el-link>
            </div>
          </el-form-item>
        </el-form>
      </div>
      <!-- 分割线 -->
      <el-divider />

      <!-- 操作按钮 -->
      <div style="margin-bottom: 15px; text-align: right">
        <el-button type="primary" size="small" @click="save">保存</el-button>
        <el-button type="success" size="small" @click="saveAndSubmit">保存并提交</el-button>
        <el-button type="info" size="small" @click="auditor">审核</el-button>
      </div>

      <!-- 详情表格 -->
      <el-table :data="detailList" style="width: 100%" border v-loading="loading">
        <!-- 操作列 -->
        <el-table-column label="操作" width="80" align="center" fixed="left">
          <template #default="scope">
            <el-button link type="danger" size="small" plain @click="removeDetailRow(scope.$index)">
              <el-icon>
                <Minus />
              </el-icon>
            </el-button>
          </template>
        </el-table-column>

        <!-- 商品 -->
        <el-table-column prop="goodsName" label="商品" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.goodsName" style="width: 95%" readonly />
          </template>
        </el-table-column>

        <!-- 采购数量 -->
        <el-table-column prop="allQuantity" label="采购数量" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.allQuantity" style="width: 95%" readonly />
          </template>
        </el-table-column>

        <!-- 采购单位 -->
        <el-table-column prop="unitName" label="单位" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.unitName" style="width: 95%" readonly />
          </template>
        </el-table-column>

        <!-- 待质检数量 -->
        <el-table-column prop="restQuantity" label="" width="180" align="center">
          <template #header>
            待质入库数量
            <el-tooltip class="box-item" content="不包含已经质检但未入库的数量" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.restQuantity" style="width: 95%" readonly />
          </template>
        </el-table-column>

        <!-- 本次质检数量 -->
        <el-table-column prop="nowQuantity" label="本次质检数量" width="180" align="center">
          <template #default="scope">
            <el-input-number v-model.number="scope.row.nowQuantity" :min="0" :step="1" style="width: 95%"
              @change="changePassPresent(scope.row)" />
          </template>
        </el-table-column>

        <!-- 本次质检合格数量 -->
        <el-table-column prop="okQuantity" label="本次合格数量" width="180" align="center">
          <template #default="scope">
            <el-input-number v-model.number="scope.row.okQuantity" :min="0" :max="scope.row.nowQuantity" :step="1"
              style="width: 95%" @change="changePassPresent(scope.row)" />
          </template>
        </el-table-column>

        <!-- 本次合格率 -->
        <el-table-column prop="passPresent" label="本次合格率" width="180" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.passPresent" style="width: 95%" readonly />
          </template>
        </el-table-column>
      </el-table>
      <br />

      <!-- 调拨单备注 -->
      <el-input v-model="qualityOrder.remark" style="width: 100%" type="textarea" placeholder="暂无备注信息" />

      <!--操作日志-->
      <div style="margin-bottom: 15px; text-align: right">
        <br />
        <el-button plain @click="router.push({ name: 'quality' })">历史记录</el-button>
        <el-button plain>操作日志</el-button>
      </div>

      <!-- 商品搜索列表弹出对话框 -->
      <FreeGoodsSelect v-model="showSelectGoods" @confirm="handleSelectedGoods" />

      <el-dialog v-model="dialogCGVisible" title="选择采购订单" width="70%">
        <CGOrderSelect ref="cGOrderRef" />
        <template #footer>
          <el-button @click="dialogCGVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCG">确定</el-button>
        </template>
      </el-dialog>

      <div style="float: right; position: relative; top: -100px; left: -250px; z-index: 10;" v-if="qualityOrder">
        <img src="@/assets/passed.png" width="120px" v-if="qualityOrder.status == 3"/>
        <img src="@/assets/waitingpass.png" width="120px" v-if="qualityOrder.status == 2"/>
        <img src="@/assets/passdefault.png" width="120px" v-if="qualityOrder.status == 0"/>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, defineProps, inject, onMounted } from "vue";
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { formatCreatedDate, formatDate } from "@/util";
import FreeGoodsSelect from "@/util/FreeGoodsSelect.vue";
import CGOrderSelect from "@/util/CGOrderSelect.vue";

let router = useRouter();
let axios = inject('axios')
let loading = ref(false);
//当前选中行
// let currentRow = ref(null), currentIndex = ref(null);
// 仅用于绑定 el-date-picker 的日期部分（YYYY-MM-DD）
const datePickerValue = ref(null)
function handleDateChange(newDateStr) {
  // newDateStr 是 YYYY-MM-DD 字符串 或 null
  qualityOrder.value.createdTime = newDateStr ? formatCreatedDate(newDateStr) : null
}
//质检单信息
const qualityOrder = ref({
  createdTime: null,
  type: '',
  status: 1, //1：已创建
  sourceOrderCode: '',
  providerId: '',
});

// //质检单详情列表
let detailList = ref([{}, {}, {}, {}, {}]);

const props = defineProps([
  "id"
])

// ------------- 选择源单 -----------------
let dialogCGVisible = ref(false), dialogXSVisible = ref(false);
console.log(dialogXSVisible);
const cGOrderRef = ref(null)
const openCGDialog = async () => {
  dialogCGVisible.value = true
}
//  ----------- CG ------------------
const confirmCG = () => {
  const selected = cGOrderRef.value.getSelectedItems()
  if (selected.length === 0) {
    ElMessage.warning('请至少选择一个采购订单')
    return
  }
  // 将源单赋值给质检单
  qualityOrder.value.sourceOrderCode = selected[0].procurement_code;
  qualityOrder.value.companyId = selected[0].companyCode;
  qualityOrder.value.partnerId = selected[0].supplier_code;
  qualityOrder.value.partnerName = selected[0].supplier_name
  qualityOrder.value.remark = selected[0].procurement_remark
  qualityOrder.value.type = 1; //采购入库1，销售退货2


  let detailArr = [];
  selected[0].detailList.forEach(i => {
    let obj = {
      goodsName: i.goods_name,
      warehouseName: i.goods_store,
      allQuantity: i.procurementDetail_num,
      restQuantity: i.procurementDetail_num - i.inspected_quantity,
      nowQuantity: i.procurementDetail_num - i.inspected_quantity, //默认本次质检所有剩余没质检的数量，如果本次不质检这么多，可以修改
      okQuantity: i.procurementDetail_num - i.inspected_quantity, //本次质检通过数量，默认为全通过
      passPresent: "100.00%", //默认全合格率
      unitPrice: i.afterDiscount_taxPrice,
      totalPrice: i.totalAmount_includingTax,
      unitName: i.goods_unit,
    }
    detailArr.push(obj);
  })
  detailList.value = detailArr;

  console.log('选中的订单:', selected[0])
  dialogCGVisible.value = false
}

// -------------------- 合格调整 ---------------------
function changePassPresent(current) {
  const now = Number(current.nowQuantity);
  const ok = Number(current.okQuantity);

  if (now <= 0 || isNaN(now) || isNaN(ok)) {
    current.passPresent = '0.00%';
  } else {
    const rate = (ok / now) * 100;
    current.passPresent = rate.toFixed(2) + '%';
  }
}

// --------------- 选择商品 ----------------
const showSelectGoods = ref(false)
// function openGoodsDialog(row, index) {
//   showSelectGoods.value = true
//   currentRow.value = row;
//   currentIndex.value = index;
//   console.log("当前选中行：", row)
// }
// 确认选择商品
const handleSelectedGoods = (selected) => {
  // selected：对话框勾选的商品数据 (里面还包括了单位列表：unitList)
  // selected.forEach(goods => { const unitList = goods.unitList })
  console.log(selected)
  // if (selected.length > 0) {
  //   //当前行后面添加选中的的商品信息
  //   let arr = [];
  //   for (let i = 0; i < selected.length; i++) {
  //     if (selected[i].managerType == 1) {
  //       showBatch.value = true; //此处应该是每次数组变化，就需要进行判断，改成watch -------------------------------未改------------------------------
  //     }
  //     let obj = {
  //       goodsId: selected[i].id,
  //       goodsCode: selected[i].code,
  //       goodsName: selected[i].code + ' ' + selected[i].name,
  //       unitId: selected[i].unit || null,
  //       unitName: selected[i].unitName || null,
  //       categoryId: selected[i].type || null,
  //       categoryName: selected[i].typeName || null,
  //       availableStock: selected[i].stock || null,
  //       specification: selected[i].specification || null,
  //       warehouseId: selected[i].warehouse || null,
  //       warehouseName: selected[i].warehouseName || null,
  //       batchNo: selected[i].type == 1 ? selected[i].batchNo : null,
  //       birthday: selected[i].type == 1 ? selected[i].birthday : null,
  //       expiration: selected[i].type == 1 ? selected[i].expiration : null,
  //       type: selected[i].managerType,
  //       quantity: 0, //默认
  //       unitPrice: 0.0,
  //       totalPrice: 0.0,
  //     }
  //     arr[i] = obj
  //   }
  //   //当前下标往后添加选中的商品
  //   detailList.value.splice(currentIndex.value, 1, ...arr);
  //   console.log("detailList", detailList.value)
  //   console.log("onGoodsSelected", selected)
  // }
}
const removeDetailRow = (index) => {
  if (detailList.value.length === 1) {
    ElMessage({
      message: '至少保留一条记录',
      type: 'warning',
    })
    return;
  }
  detailList.value.splice(index, 1);
}

// =================== validSave =======================
let originalOrder = ref(null), originalDetailList = ref(null)
let filteredDetailList = ref(null)
function validSave() {
  // 1. 必须关联源单
  if (!qualityOrder.value.sourceOrderCode) {
    ElMessage.warning('请先选择关联的采购订单或销售退货单');
    return false;
  }
  filteredDetailList.value = detailList.value.filter(item => {
    // 检查 goods 是否不为空
    return item.goodsName;
  });
  // 2. 明细不能为空
  if (!filteredDetailList.value || filteredDetailList.value.length == 0) {
    ElMessage.warning('质检明细不能为空');
    return false;
  }


  // 3. 遍历明细校验
  for (let i = 0; i < filteredDetailList.value.length; i++) {
    const row = filteredDetailList.value[i];
    // 3.1 本次质检数量必须 > 0
    const nowQty = Number(row.nowQuantity);
    if (isNaN(nowQty) || nowQty <= 0) {
      ElMessage.warning(`第 ${i + 1} 行：本次质检数量必须大于 0`);
      return false;
    }

    // 3.2 本次合格数量不能为负
    const okQty = Number(row.okQuantity);
    if (isNaN(okQty) || okQty < 0) {
      ElMessage.warning(`第 ${i + 1} 行：本次合格数量不能小于 0`);
      return false;
    }

    // 3.3 合格数量不能超过质检数量
    if (okQty > nowQty) {
      ElMessage.warning(`第 ${i + 1} 行：本次合格数量不能大于本次质检数量`);
      return false;
    }
    const restQty = Number(row.restQuantity);
    if (restQty < nowQty) {
      ElMessage.warning(`第 ${i + 1} 行：本次质检数量不能大于待质检数量`);
      return false;
    }
  }

  return true; // 校验通过
}

// ------------------- save() ------------------------
function save() {
  if (props.id) { //修改
    if (validSave()) {
      console.log("修改")
      modify();
    }
  } else { //新增
    console.log("新增")
    if (validSave())
      add();
  }
}

function saveAndSubmit() {
  qualityOrder.value.status = 2;
  save();
}

async function auditor() {
  const rs = await axios({
    url: '/xyy/quality/auditor',
    method: 'post',
    data: {
      qualityInspection: qualityOrder.value,
      qualityInspectionItemList: detailList.value,
    }
  })
  if (rs.data.code == 5200) {
    ElMessage({ message: rs.data.msg, type: 'success' })
    router.push({ name: 'quality' })
  } else {
    ElMessage({ message: rs.data.msg, type: 'danger' })
  }

}
// ------------------ add ------------------

const add = async () => {
  const rs = await axios({
    url: '/xyy/quality/create',
    method: 'post',
    data: {
      qualityInspection: qualityOrder.value,
      qualityInspectionItemList: detailList.value,
    }
  })
  if (rs.data.code == 5200) {
    ElMessage({ message: rs.data.msg, type: 'success' })
    router.push({ name: 'quality' })
  } else {
    ElMessage({ message: rs.data.msg, type: 'danger' })
  }
}
// ------------------ modify ------------------
async function modify() {
  //1.map根据id快速获取原数组
  const originalMap = new Map(
    originalDetailList.value.map(item => [item.id, item])
  );
  //2.遍历当前列表：找新增 & 修改
  let addList = [], delList = [], modList = [];
  filteredDetailList.value.forEach(i => {
    if (!i.id) {
      addList.push(i); //新增
    } else {
      if (hasModifiedDetail(i, originalMap.get(i.id))) {
        modList.push(i);
      }
      //map数据比较过就删除， map中数据 - 当前明细 = 已删除数据
      originalMap.delete(i.id);
    }
  })
  //3.剩下的 originalMap 中的 id 就是被删除的
  for (const id of originalMap.keys()) {
    delList.push(id);
  }
  console.log(addList)
  console.log(delList)
  console.log(modList)
  //提交修改
  try {
    const rs = await axios({
      url: `/xyy/quality/modify`,
      method: 'post',
      data: {
        orderModified: hasModifiedOrder(originalOrder.value, qualityOrder.value),
        addList: addList,
        modList: modList,
        delList: delList,
        qualityInspection: qualityOrder.value
      }
    })
    if (rs.data.code == 5200) {
      ElMessage({ message: "修改质检单成功", type: 'success', });
      router.push({ name: 'quality' });
      return;
    }
    ElMessage({ message: "修改质检单失败", type: 'danger', });
  } catch (error) {
    console.log(error);
    ElMessage({ message: `修改质检单异常:${error.msg}`, type: 'danger', });
  }
}

//判断当前 质检明细 是否修改
function hasModifiedDetail(current, original) { //判断这个商品是否修改的前提：商品id或code存在，其他：商品单位、仓库、批次号、库位、数量、单价修改即表示该明细修改了
  const fields = ["nowQuantity", "okQuantity"];
  return fields.some(field => current[field] != original[field]);
}
//判断当前 质检单 是否修改
function hasModifiedOrder(current, original) {
  const fields = ["createdTime", "remark", "status", "sourceOrderCode"]
  return fields.some(field => current[field] != original[field]);
}
// ------------------ init ------------------

function init() {
  axios({
    url: '/xyy/quality/get/' + props.id,
    method: 'post',
  }).then(rs => {
    if (rs.data.code == 5200 && rs.data.qualityRequest) {
      qualityOrder.value = rs.data.qualityRequest.qualityInspection;
      datePickerValue.value = qualityOrder.value.createdTime;
      // 获取明细列表
      const list = rs.data.qualityRequest.qualityInspectionItemList || [];
      // 👇 关键：为每行计算 passPresent
      list.forEach(row => {
        // 确保字段存在且为数字
        const now = Number(row.nowQuantity) || 0;
        const ok = Number(row.okQuantity) || 0;

        if (now > 0 && !isNaN(ok)) {
          const rate = (ok / now) * 100;
          row.passPresent = rate.toFixed(2) + '%';
        } else {
          row.passPresent = '0.00%';
        }
      });
      detailList.value = list
      //深拷贝一份初始数据，方便后面操作
      originalDetailList.value = JSON.parse(JSON.stringify(detailList.value));
      originalOrder.value = JSON.parse(JSON.stringify(qualityOrder.value));
      console.log("detailList", detailList.value);
    }
  })
}
// ----------------- onMounted -------------------
onMounted(() => {
  //如果是修改，获取到入库单和入库明细
  if (props.id) {
    init();
  } else {
    detailList.value = [{

    }]
    qualityOrder.value.createdTime = formatDate(new Date());
    datePickerValue.value = qualityOrder.value.createdTime.substring(0, 10)
  }
})
</script>

<style></style>